package com.kvest.fortests.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.Engine;
import android.util.Log;
import android.view.View;
import com.kvest.fortests.R;
import com.kvest.fortests.broadcastreceiver.DynamicBroadcastReceiver;
import com.kvest.fortests.broadcastreceiver.StaticBroadcastReceiver;
import com.kvest.fortests.service.EmptyService;
import com.kvest.fortests.service.RepeatedService;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ForTestsActivity extends Activity {
    private static final int TTS_DATA_CHECK = 7;
    private static final int VOICE_RECOGNITION = 8;
    private static final int GET_PICTURE = 9;
    private static final String DYNAMIC_BROADCAST_ACTION = "com.kvest.fortests.broadcastreceiver.DYNAMIC_RECEIVER";

    private TextToSpeech tts;

    private DynamicBroadcastReceiver br1;
    private DynamicBroadcastReceiver br2;
    private BroadcastReceiver emptyServiceBroadcastReceiver;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        printCoordinates();

        br1 = new DynamicBroadcastReceiver("br1");
        br2 = new DynamicBroadcastReceiver("br2");
        emptyServiceBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("KVEST_TAG", "emptyServiceBroadcastReceiver=" + intent.getAction());
                Log.d("KVEST_TAG", EmptyService.ACTION_PARAM + "=" + intent.getStringExtra(EmptyService.ACTION_PARAM));
            }
        };

        Log.d("KVEST_TAG", getString(R.string.with_params, 7, -7));
        Log.d("KVEST_TAG", getString(R.string.with_string_params, "STRING_PARAM"));

        Log.d("KVEST_TAG", "ExternalCacheDir=" + getExternalCacheDir().getAbsolutePath());
        Log.d("KVEST_TAG", "CacheDir=" + getCacheDir().getAbsolutePath());

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) && isCameraIntentAvailable(getApplicationContext(), PackageManager.FEATURE_CAMERA)) {
            findViewById(R.id.take_picture_btn).setEnabled(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter(DYNAMIC_BROADCAST_ACTION);
        registerReceiver(br1, intentFilter);
        registerReceiver(br2, intentFilter);

        registerReceiver(emptyServiceBroadcastReceiver, new IntentFilter(EmptyService.BROADCAST_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();

        unregisterReceiver(br1);
        unregisterReceiver(br2);

        unregisterReceiver(emptyServiceBroadcastReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (tts != null) {
            tts.shutdown();
        }
    }

    public void onShowUITestActivityClick(View view) {
        startActivity(new Intent(this, UITestActivity.class));
    }

    public void onStartEmptyServiceClick(View view) {
        startService(new Intent(getApplicationContext(), EmptyService.class));
    }

    public void onStopEmptyServiceClick(View view) {
        stopService(new Intent(getApplicationContext(), EmptyService.class));
    }

    public void onStartRepeatedServiceClick(View view) {
        startService(new Intent(getApplicationContext(), RepeatedService.class));

//        AlarmManager am = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
//
//        Intent intent = new Intent(getApplicationContext(), RepeatedService.class);
//        PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
//
//        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60 * 1000, 60 * 1000, pi);
    }

    public void onCancelAlarmClick(View view) {
        Intent intent = new Intent(getApplicationContext(), RepeatedService.class);
        PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, intent, 0);


        AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);
    }

    public void onSecondActivityClick(View view) {
        startActivity(new Intent("com.kvest.START_SECOND_ACTIVITY"));
    }

    public void onInitTTSClick(View view) {
        Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(intent, TTS_DATA_CHECK);
    }

    public void onTTSClick(View view) {
        if (tts != null) {
            tts.speak("This is text to speech test", TextToSpeech.QUEUE_ADD, null);
        }
    }

    public void onVITClick(View view) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "This is prompt");
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
        startActivityForResult(intent, VOICE_RECOGNITION);
    }

    public void onStaticBroadcastClick(View view) {
        Intent intent = new Intent(StaticBroadcastReceiver.ACTION);
        intent.putExtra("param1", "THis is param1");
        intent.putExtra("param2", 2);
        sendBroadcast(intent, "com.kvest.permission.BROADCAST_PERMISSION");
    }

    public void onDinamicBroadcastClick(View view) {
        Intent intent = new Intent(DYNAMIC_BROADCAST_ACTION);
        intent.putExtra("param1", "THis is param1");
        intent.putExtra("param2", 2);
        sendBroadcast(intent, "com.kvest.permission.BROADCAST_PERMISSION");
    }

    public void onGetBatteryStatusClick(View view) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

        float batteryPct = level / (float)scale;
        Log.d("KVEST_TAG", "level=" + level + " scale=" + scale + " batteryPct=" + batteryPct);
    }

    public void onTakePictureClick(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = createImageFile();
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, GET_PICTURE);
    }

    public static boolean isCameraIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private void printCoordinates() {
        LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if (location != null) {
            Log.d("KVEST_TAG", "location = " + location.toString());
        } else {
            Log.d("KVEST_TAG", "location == null");
        }
    }

    private File createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return new File("/mnt/sdcard/Kvest_logs/" + timeStamp + ".jpg");
    }

    @Override
    protected void onActivityResult(int request, int result, Intent intent) {
        if (request == TTS_DATA_CHECK) {
            if (result == Engine.CHECK_VOICE_DATA_PASS) {
                tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int status) {
                        if (status == TextToSpeech.SUCCESS) {
                            tts.setLanguage(Locale.ENGLISH);
                            findViewById(R.id.tts_btn).setEnabled(true);
                        }
                    }
                });
            } else {
                Log.d("KVEST_TAG", "ACTION_INSTALL_TTS_DATA");
                startActivity(new Intent(Engine.ACTION_INSTALL_TTS_DATA));
            }
        } else if (request == VOICE_RECOGNITION) {
            if (result == RESULT_OK) {
                ArrayList<String> results = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                Log.d("KVEST_TAG", "VOICE_RECOGNITION RESULTS:");
                for (String string : results) {
                    Log.d("KVEST_TAG", "[" + string + "]");
                }
            } else {
                Log.d("KVEST_TAG", "VOICE_RECOGNITION ERROR");
            }
        } else if (request == GET_PICTURE) {
            if (result == RESULT_OK) {
                Log.d("KVEST_TAG", "Take picture ok");
            } else {
                Log.d("KVEST_TAG", "Cancel take picture");
            }
        }
    }

    public void onShowLayoutPerformanceActivityClick(View view) {
        startActivity(new Intent(this, LayoutPerformanceActivity.class));
    }

    public void onNavigationDrawerTestClick(View view) {
        startActivity(new Intent(this, NavigationDrawerActivity.class));
    }

    public void onShowFragmentTestClick(View view) {
        startActivity(new Intent(this, FragmentHostActivity.class));
    }
}
